<template>
	<view class="page-container back-grey">
		<view class="prow-l back-white mb-base" style="padding: 32rpx;">
			<u-search placeholder="请输入学校名字" :action-style="{'color': primaryColor, 'fontWeight': 'true'}" v-model="keyword" @search="search" @custom="search"></u-search>
		</view>
		<view class="prow-base back-white">
			<view v-for="(item, index) in show" :key="index" class="row-box college-item" @click="selectCollege(item)">
				<text>{{ item.name }}</text>
			</view>
		</view>
	</view>
</template>

<script>
	import { mapState, mapMutations } from "vuex"
	export default {
		data() {
			return {
				keyword: '', // 搜索关键词
				pageSize: 10, // 每页数据量
				pageIndex: 1, // 第几页
				pageCount: 0, // 总页数
				list: [], // 完整数据列表
				show: [], // 展示的列表
			};
		},
		onLoad() {
			this.getList(0)
		},
		onPullDownRefresh() {
			this.getList(0)
		},
		onReachBottom() {
			this.getList(1)
		},
		methods: {
			...mapMutations('m_user', ['updateCollege']),
			
			// 搜索学校名字
			search(value) {
				var reg = new RegExp(this.keyword)
				let list = this.deepClone(this.list)
				this.show = list.filter((item, index) => {
					return reg.test(item.name)
				})
			},
			
			// 选择学校
			selectCollege(item) {
				// 获取所有页面栈实例列表
				let pages = getCurrentPages()
				// 上一页页面实例
				let prevPage = pages[ pages.length - 2 ]
				if (prevPage.route == 'pages/index/index') { // 上一页是首页
					// 将选择的学校id和name保存到缓存里
					this.updateCollege({
						collegeId: item.id,
						collegeName: item.name
					})
				} else {
					// 修改上一页data里面的参数值
					prevPage.$vm.schoolId = item.id
					prevPage.$vm.schoolName = item.name
				}
				uni.navigateBack()
			},
			
			// 获取学校
			getList(condition) {
				// 判断情况， 0新获取 1分页
				if (condition == 0) {
					this.pageIndex = 1
				}else if (this.pageIndex < this.pageCount) {
					this.pageIndex += 1
				}
				this.$api.GetCollegeList({
					current: this.pageIndex,
					limit: this.pageSize
				}).then(res => {
					console.log('GetCollegeList-success', res)
					if (res.data.code == 200) {
						// 请求成功后
						if (this.pageIndex == 1) {
							this.list = [{ id: null, name: "全部" }, ...res.data.data.records]
							this.pageCount = res.data.data.pages
						} else {
							this.list = [...this.list, ...res.data.data.records]
						}
						// 克隆列表展示
						this.show = this.deepClone(this.list)
					}
				}).catch(err => {
					console.log('GetCollegeNameList-fail', err)
				})
			}
		},
	}
</script>

<style lang="scss">
	.college-item {
		height: 88rpx;
		border-bottom: 1rpx solid #f2f2f2;
		&:last-child {
			border-bottom: none;
		}
	}
</style>
